package jetbrains.buildServer.cuta.logic.operators;

import jetbrains.buildServer.cuta.logic.ColumnDef;
import jetbrains.buildServer.cuta.logic.sheet.Cell;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import java.util.regex.Pattern;

import static jetbrains.buildServer.cuta.utils.DomUtil.getAttrString;



/**
 * @author Leonid Bushuev from JetBrains
 */

class JoinLinesOperator extends AbstractOperator
{
    String mySeparator = " ";
    String myHeader = "";
    String myFooter = "";
    String myStub = "";


    @Override
    public void init(Element element, ColumnDef column, ExternalContext extContext)
    {
        mySeparator = getAttrString(element, "separator", " ");
        myHeader = getAttrString(element, "header", "");
        myFooter = getAttrString(element, "footer", "");
        myStub = getAttrString(element, "stub", "");
    }


    private static final Pattern NLPattern =
            Pattern.compile("\n[\\s\n]*", Pattern.DOTALL);


    @Override
    public void run(Object object, Cell cell)
    {
        String text = cell.getText().trim();

        if (text.length() > 0)
            text = myHeader
                 + NLPattern.matcher(text).replaceAll(mySeparator)
                 + myFooter;
        else
            text = myStub;

        cell.setText(text);
    }


    @NotNull
    @Override
    public String name()
    {
        return "join-lines";
    }


    @Override
    public String toString()
    {
        return name();
    }
}
